/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject;

import com.inspur.edp.lcm.metadata.api.entity.ExtractContext;
import com.inspur.edp.lcm.metadata.spi.ExtractAction;
import com.inspur.edp.web.common.constant.FrontendProjectConstant;
import com.inspur.edp.web.common.entity.TerminalType;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.metadata.GspProjectUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 前端工程提取器
 */
@Slf4j
public class FrontendProjectExtractor implements ExtractAction {

    /**
     * 提取生成物到指定目录
     *
     * @param context
     */
    @Override
    public void extract(ExtractContext context) {
        if (context == null || StringUtility.isNullOrEmpty(context.getProjectPath())) {
            return;
        }
        // 目录A->(拷贝)->目录B
        String projectName = GspProjectUtility.getProjectName(context.getProjectPath());

        extract(context, projectName, TerminalType.PC);
        extract(context, projectName, TerminalType.MOBILE);
    }

    /**
     * 提取交付物
     *
     * @param context      提取交付物上下文参数
     * @param terminalType 类型 分为PC和移动
     */
    private void extract(ExtractContext context, String projectName, TerminalType terminalType) {

        String projectPath = context.getProjectPath();
        // TODO: 规范工程类型后，开放这部分代码
        // string projectType = FrontendProjectUtility.GetProjectType(projectPath);
        // if (projectType != "frontend") // 非前端工程，直接返回
        // {
        //     return;
        // }
        // 表单元数据打包后目录
        String sourceExtractPath = getSourceExtractPath(projectPath, projectName, terminalType, false);

        boolean isSourcePathExists = FileUtility.exists(sourceExtractPath);
        if (!isSourcePathExists) {
            return;
        }

        String targetExtractBasePath = getTargetBaseExtractPath(context, projectPath, projectName, terminalType);

        copyFrontendProjectExtract(projectName, sourceExtractPath, targetExtractBasePath, terminalType);

        // 表单发布 不提取解析表单
//        if (terminalType == TerminalType.PC) {
//            // 提取解析脚本到publish目录
//            projectPath = FileUtility.combine(projectPath, "metadata");
//            String sourceDynamicFormJs = TerminalType.PC.getResolveBasePath(projectPath, true);
//            if (FileUtility.exists(sourceDynamicFormJs)) {
//                String formPublishPath = terminalType.getPublishPathName();
//                String targetExtractPath = FileUtility.combine(targetExtractBasePath, formPublishPath, projectName);
//                FileUtility.copyFolder(sourceDynamicFormJs, targetExtractPath);
//            }
//        }

        copyI18nResource(projectPath, targetExtractBasePath, projectName, terminalType);
    }

    /**
     * 获取源路径
     *
     * @param projectPath
     * @param projectName
     * @param terminalType
     * @return
     */
    private String getSourceExtractPath(String projectPath, String projectName, TerminalType terminalType, boolean isJieXiForm) {
        String projectProductPath = terminalType.getDeployableProjectRelativePath(isJieXiForm);
        return FileUtility.combine(projectPath, "metadata", projectProductPath, projectName);
    }

    private String getTargetBaseExtractPath(ExtractContext context, String projectPath, String projectName, TerminalType terminalType) {
        String targetExtractBasePath = "";
        if (context.getDeployPath().indexOf(context.getProjectPath()) == 0) {
            // 表示部署路径和工程路径一致
            // projectPath C:\projects\publish\publish\publish\bo-publishfrontpublish
            // deployPath  C:\projects\publish\publish\publish\bo-publishfrontpublish\publish\server\apps\publish\publish
            String[] publishPath = FileUtility.getPlatformIndependentPath(context.getDeployPath()).substring(FileUtility.getPlatformIndependentPath(context.getProjectPath()).length()).split("/");
            List<String> publishPathSplitList = Arrays.stream(publishPath).filter(t -> !StringUtility.isNullOrEmpty(t)).collect(Collectors.toList());
            if (publishPathSplitList.size() >= 2) {
                publishPathSplitList.set(1, "web");
                String generateFullPublishPath = String.join("/", publishPathSplitList);
                generateFullPublishPath = FileUtility.combine(context.getProjectPath(), generateFullPublishPath);
                return generateFullPublishPath;
            }
        }
        int lastPublishIndex = context.getDeployPath().lastIndexOf(FrontendProjectConstant.PROJECT_PUBLISH_PATH);
        if (lastPublishIndex != -1) {
            targetExtractBasePath = FileUtility.combine(context.getDeployPath().substring(0, lastPublishIndex + FrontendProjectConstant.PROJECT_PUBLISH_PATH.length()), "web", context.getDeployPath().substring(lastPublishIndex + FrontendProjectConstant.PROJECT_PUBLISH_PATH.length() + 1 + "nstack".length() + 1));
        } else {
            targetExtractBasePath = FileUtility.combine(projectPath, FrontendProjectConstant.PROJECT_PUBLISH_PATH, "web", context.getDeployPath());
        }

        return targetExtractBasePath;
    }

    private void copyI18nResource(String projectPath, String targetPath, String projectName, TerminalType terminalType) {
        String i18nResourceRelavtivePath = terminalType.getWebDevI18nRelativePath();
        String sourceI18nResourcePath = java.nio.file.Paths.get(projectPath).resolve(i18nResourceRelavtivePath).toString();

        String formPublishPath = terminalType.getPublishPathName();
        String targetI18nResourcePath = FileUtility.combine(targetPath, formPublishPath, projectName);

        if ((new java.io.File(sourceI18nResourcePath)).isDirectory()) {
            FileUtility.copyFolder(sourceI18nResourcePath, targetI18nResourcePath);
        }
    }


    /**
     * 拷贝前端工程提取物到部署目录
     */
    private void copyFrontendProjectExtract(String projectName, String sourceExtractPath, String targetExtractBasePath, TerminalType terminalType) {
        log.debug(String.format("Debug_CopyFrontendProjectExtract: projectName: %1$s, sourcePath: %2$s, destinationBasePath: %3$s", projectName, sourceExtractPath, targetExtractBasePath));

        if (StringUtility.isNullOrEmpty(projectName) || StringUtility.isNullOrEmpty(sourceExtractPath) || StringUtility.isNullOrEmpty(targetExtractBasePath)) {
            return;
        }
        String formPublishPath = terminalType.getPublishPathName();
        String targetExtractPath = FileUtility.combine(targetExtractBasePath, formPublishPath, projectName);
        copyExtract(sourceExtractPath, targetExtractPath);
    }

    /**
     * 拷贝提取物到指定目录
     */
    private void copyExtract(String sourcePath, String destinationPath) {
        if (StringUtility.isNullOrEmpty(sourcePath) || StringUtility.isNullOrEmpty(destinationPath)) {
            return;
        }

        FileUtility.copyFolder(sourcePath, destinationPath);
    }
}
